package com.ay.weixin.fdc.boss.yongjin.event;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;

import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.util.ExcelUtils;
import org.lizar.util.StringHelper;
import org.lizar.util.pager.PageData;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.admin.category.domain.CategoryLoader;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.admin.superadmin.domain.SuperAdmin;
import com.ay.weixin.fdc.boss.bank.db.BankAccountDao;
import com.ay.weixin.fdc.boss.bank.domain.BankAccount;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;
import com.ay.weixin.fdc.boss.user.db.UserDao;
import com.ay.weixin.fdc.boss.user.db.WeiXinInfoDao;
import com.ay.weixin.fdc.boss.user.domain.FDCAgentDetail;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashWithdrawFlowDao;
import com.ay.weixin.fdc.boss.yongjin.domain.CashFlow;
import com.ay.weixin.fdc.boss.yongjin.domain.CashWithdrawFlow;
import com.ay.weixin.fdc.boss.yongjin.domain.Withdraw;
import com.ay.weixin.mail.domain.Email;
import com.ay.weixin.templatereply.domain.ReplyMsg;
import com.ay.weixin.templatereply.domain.TemplateReply;

public class YongJinMC extends Event{

	private IbatisProjectDao project_dao;
	private CategoryLoader cl;
	private IbatisCashFlow cash_flow;
	private IbatisCashWithdrawFlowDao withdraw_flow_dao;
	private UserDao user_dao;
	private BankAccountDao bank_dao;
	private static WeiXinInfoDao weixin_dao;
	@Override
	public void init_property() throws Exception {
		project_dao=Container.get(IbatisProjectDao.class);
		cl=Container.get(CategoryLoader.class);
		cash_flow=Container.get(IbatisCashFlow.class);
		withdraw_flow_dao=Container.get(IbatisCashWithdrawFlowDao.class);
		user_dao=Container.get(UserDao.class);
		bank_dao=Container.get(BankAccountDao.class);
		weixin_dao=Container.get(WeiXinInfoDao.class);
		
		}

	@Override
	public String default_handling_path() {
		return "/mc/yongjin/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		Customer customer=(Customer)el.getSessionAttr("customer");
		if(customer==null){
			el.response_to_root(CustomerLogin.login_path());
		}else{
			if(el.queryPathCheck(2, "")){
				index(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(2, "approve_update")){
				approve(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(2, "view_setting")){
				view_setting(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(2, "setting")){
				setting(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(2, "user_detail")){
				user_detail(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(2, "batch_export")){
				batch_export(el,customer.getWxprojectID());
			}
		}
	}
	
	private void batch_export(EventLoader el,long wxproject_id) throws IOException{
		int status=el.getInt("out_status",Withdraw.OUT_STATUS_APPLY);
		String keywords=el.param("keywords","", "utf-8");
		
		List<Withdraw> withdraw_list=null;
		
		try {
			if(StringHelper.isNull(keywords)){
				withdraw_list=cash_flow.getWithdraw(wxproject_id,status);
			}else{
				withdraw_list=cash_flow.getWithdrawByName(wxproject_id,status,keywords);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
		}
		
		if(withdraw_list==null){
			withdraw_list=new LinkedList<Withdraw>();
		}
		
		List<List<String>> data=new LinkedList<List<String>>();
		List<String> titles=new LinkedList();
		data.add(titles);
		titles.add("用户名");
		titles.add("提现状态");
		titles.add("户名");
		titles.add("卡号");
		titles.add("银行");
		titles.add("分行名");
		titles.add("提现金额");
		titles.add("申请时间");
		titles.add("日志");
		
		for(Withdraw withdraw:withdraw_list){
			List<String> row=new LinkedList();
			row.add(withdraw.getUser_name());
			row.add(withdraw.outStatusExpress());
			row.add(withdraw.getAccount_name());
			row.add(withdraw.getAccount());
			row.add(withdraw.getBank_name());
			row.add(withdraw.getBank_subname());
			row.add(Float.toString(withdraw.getCash()));
			row.add(withdraw.getTs_time());
			row.add(withdraw.getLogs());
			
			
			data.add(row);
		}
		el.response().setContentType("application/vndms-excel");
		
		File output=new File(el.getRealPath("/upload/xls/cache"));
		if(!output.exists()){
			output.mkdirs();
		}
		File file=new File(el.getRealPath("/upload/xls/cache/yongjin.xls"));
		
		
		ExcelUtils.writeExcel("佣金提现信息", data, file);
		
		el.response_to_root("/upload/xls/cache/yongjin.xls");
		
	}
	
	private void user_detail(EventLoader el,long wxproject_id) throws IOException, ServletException{
		Long id=el.getLong("id");
		UserBasic user=null;
		try {
			user=user_dao.getById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			index(el,wxproject_id);
			return;
		}
		if(user==null){
			index(el,wxproject_id);
			return;
		}
		
		List<CashFlow> list=null;
		float closed_commission=0;
		float total=0;
		try {
			list=cash_flow.getTotalFlowFisrtPage(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		try {
			total=cash_flow.countSpecificInStatusFlow(user.getId(),CashFlow.IN_STATUS_IN);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",  el.i18("bank.db.failure"));
		}
		
		try {
			closed_commission=cash_flow.countCashAll(user.getId(),CashFlow.FLOW_OUT);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",  el.i18("bank.db.failure"));
		}
		
		List<BankAccount> bank_list=null;
		
		try {
			bank_list=bank_dao.getByUserId(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",  el.i18("bank.db.failure"));
		}
		el.setAttr("user_detail",user);
		el.setAttr("bank_list",bank_list);
		el.setAttr("bank_category",cl.get("bank"));
		
		el.setAttr("list",list);
		
		el.setAttr("total",total);
		el.setAttr("closed_commission",closed_commission);
		el.template("/WEB-INF/template/boss/yongjin/user_detail.vm");
	}
	
	/**
	 * 
	 * 
	 {{first.DATA}}

申请时间：{{createTime.DATA}}
业务类型：{{businessType.DATA}}
在途存：{{buyMoney.DATA}}
在途取：{{sellAmount.DATA}}
{{remark.DATA}}
	 * 
	 * 
	 * */
	public static void withdraw(long wxproject_id,String title,long user_id,String applicationTime,String status,float money,String remark){
		UserWeiXinInfo weixin=null;
		try {
			weixin = weixin_dao.getByUserId(user_id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if(weixin==null||StringHelper.isNull(weixin.getId()))return;
		
		JObject params=new JObject();
		JObject first=new JObject();
		first.put("value", title);
		first.put("color", ReplyMsg.BLUE);
		params.put("first", first);
		
		JObject createTime=new JObject();
		createTime.put("value",applicationTime);
		createTime.put("color", ReplyMsg.BLUE);
		params.put("createTime", createTime);
		
		JObject businessType=new JObject();
		businessType.put("value", status);
		businessType.put("color", ReplyMsg.BLUE);
		params.put("businessType", businessType);
		
		JObject sellAmount=new JObject();
		sellAmount.put("value", money);
		sellAmount.put("color", ReplyMsg.RED);
		params.put("sellAmount", sellAmount);
		
		JObject _remark=new JObject();
		_remark.put("value", remark);
		_remark.put("color", ReplyMsg.BLUE);
		params.put("remark", _remark);
		
		ReplyMsg msg=new ReplyMsg();
		msg.setMsg_link("");
		msg.setOpenid(weixin.getId());
		msg.setWxproject_id(wxproject_id);
		msg.setTemplate_id(ProjectConfig.getStr(wxproject_id,"fdc_cash_flow.withdraw_template_id"));
		msg.setTopcolor(ReplyMsg.BLUE);
		msg.setData_params(params);
		TemplateReply.asyReply(msg);
	}
	
	private void setting(EventLoader el,long wxproject_id) throws IOException, ServletException{
		String withdraw_more_than=el.getStr("withdraw_more_than");
		String withdraw_days_limit=el.getStr("withdraw_days_limit");
		int page_size=el.getInt("page_size");
		String fdc_cash_flow_submit_notify_email=el.getStr("fdc_cash_flow_submit_notify_email");
		if(!el.paramIsFloat("withdraw_more_than")){
			el.setAttr("msg",el.i18("mc.yongjin_withdraw_more_than.must.be.float"));
			view_setting(el,wxproject_id);
			return;
		}
		
		if(!el.paramIsInteger("withdraw_days_limit")){
			el.setAttr("msg",el.i18("mc.fdc.yongjin_withdraw_days_limit.must.be.int"));
			view_setting(el,wxproject_id);
			return;
		}
		
		if(!el.paramIsInteger("page_size")){
			el.setAttr("msg",el.i18("mc.fdc.yongjin_page_size.must.be.int"));
			view_setting(el,wxproject_id);
			return;
		}
		if(!Email.isEmail(fdc_cash_flow_submit_notify_email)){
			el.setAttr("msg",String.format(el.i18("mc.email.format.wrong"), fdc_cash_flow_submit_notify_email));
			view_setting(el,wxproject_id);
			return;
		}
		
		

		
		
		String msg=null;
		try {
			ProjectConfig.update(wxproject_id,"fdc_cash_flow.withdraw_more_than",withdraw_more_than);
			
			ProjectConfig.update(wxproject_id,"fdc_cash_flow.withdraw_days_limit",withdraw_days_limit);
			
			ProjectConfig.update(wxproject_id,"fdc_cash_flow.page_size",page_size);
			
			ProjectConfig.update(wxproject_id,"fdc_cash_flow.submit_notify_enable",el.getBool("fdc_cash_flow_submit_notify_enable"));
			
			ProjectConfig.update(wxproject_id,"fdc_cash_flow.submit_notify_email",fdc_cash_flow_submit_notify_email);
		} catch (Exception e) {
			e.printStackTrace();
			msg=el.i18("mc.yongjin.default_msg_reply.failured")+":"+e.getMessage();
		}
		if(msg==null){
			msg=el.i18("mc.yongjin.setting.success");
		}
		el.setAttr("msg",msg);
		
		view_setting(el,wxproject_id);
	}
	
	private void view_setting(EventLoader el,long wxproject_id) throws IOException, ServletException{
		
		el.setAttr("withdraw_more_than",ProjectConfig.getInt(wxproject_id,"fdc_cash_flow.withdraw_more_than"));
		el.setAttr("withdraw_days_limit", ProjectConfig.getInt(wxproject_id,"fdc_cash_flow.withdraw_days_limit"));
		el.setAttr("page_size", ProjectConfig.getInt(wxproject_id,"fdc_cash_flow.page_size"));
		el.setAttr("fdc_cash_flow_submit_notify_enable", ProjectConfig.getBool(wxproject_id,"fdc_cash_flow.submit_notify_enable"));
		el.setAttr("fdc_cash_flow_submit_notify_email", ProjectConfig.getStr(wxproject_id,"fdc_cash_flow.submit_notify_email"));
		
		
		el.template("/WEB-INF/template/boss/yongjin/setting.vm");
	}
	

	
	private String statusDesc(int status){
		if(status==CashFlow.OUT_STATUS_APPLY){
			return "审核中";
		}else if(status==CashFlow.OUT_STATUS_APPROVE){
			return "审核通过，等待转账";
		}else if(status==CashFlow.OUT_STATUS_TRANSFERED){
			return "已转账，等待核实";
		}else if(status==CashFlow.OUT_STATUS_CONFIRMED){
			return "提现成功，已确认到账";
		}
		return "";
	}
	
	
	private void approve(EventLoader el,long wxproject_id) throws IOException, ServletException{
		long id=el.getLong("id");
		String log=el.getStr("log");
		int status=el.getInt("status");
		boolean reject=el.getBool("reject");
		String status_desc=statusDesc(status);
		
		if(status_desc==null){
			el.setAttr("msg",el.i18("mc.yongjin.unknown.status"));
			index(el,wxproject_id);
			return;
		}
		
		CashFlow cash=null;
		
		try {
			cash=cash_flow.get(id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if(cash==null){
			el.setAttr("msg",el.i18("mc.yongjin.record.not.exist"));
			index(el,wxproject_id);
			return;
		}
		if(reject&&StringHelper.isNull(log)){
			el.setAttr("msg",el.i18("mc.yongjin.reject.reason.needed"));
			index(el,wxproject_id);
			return;
		}
		
		if(reject){
			cash.setLogs("["+Calendar.getInstance().getTime().toLocaleString()+"][问题反馈]"+log.trim()+"<br/>"+cash.getLogs());
		}else{
			if(StringHelper.isNull(status_desc)){
				cash.setLogs("["+Calendar.getInstance().getTime().toLocaleString()+"][更新]"+log.trim()+"<br/>"+cash.getLogs());
			}else{
				cash.setLogs("["+Calendar.getInstance().getTime().toLocaleString()+"][状态更新=>"+status_desc+"]"+log.trim()+"<br/>"+cash.getLogs());
			}
			
		}
		
		
		if(!reject){
			cash.setOut_status(status);
		}
		try {
			cash_flow.update_approve(cash);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if(!reject&&status==CashFlow.OUT_STATUS_CONFIRMED){
			try {
				cash_flow.update_in_status_cash_to_out(cash.getUser_id());
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
				index(el,wxproject_id);
				return;
			}
			withdraw(wxproject_id,"佣金提取(成功)", cash.getUser_id(),new Date( cash.getTimestamp()).toLocaleString(), "佣金提取", cash.getCash(), "佣金提取成功，财务已转账，请等待查收");
		}
		
		SuperAdmin adm=el.getSessionAttr("adm",SuperAdmin.class);
		
		CashWithdrawFlow draw_flow=new CashWithdrawFlow();
		draw_flow.setDraw_id(cash.getId());
		draw_flow.setOper(adm.getId());
		draw_flow.setOper_timestamp(System.currentTimeMillis());
		draw_flow.setStatus(CashFlow.OUT_STATUS_APPROVE);
		draw_flow.setRemark(log.trim());
		
		try {
			withdraw_flow_dao.insert(draw_flow);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		el.setAttr("msg",el.i18("mc.yongjin.update.success"));
		index(el,wxproject_id);
		
	}
	

	
	private void index(EventLoader el,long wxproject_id) throws IOException, ServletException{
		int status=el.getInt("out_status",Withdraw.OUT_STATUS_APPLY);
		String keywords=el.param("keywords","", "utf-8");
		int page=el.getInt("page",1);
		int size=Keys.getInt("sys_page_size");
		int total=0;
		String msg=null;
		
		try{
			if(StringHelper.isNull(keywords)){
				total=cash_flow.countByOutStatus(wxproject_id,status);
			}else{
				total=cash_flow.countByOutStatusAndName(wxproject_id,status,keywords);
			}
		}catch(Exception e){
			e.printStackTrace();
			el.setAttr("msg", el.i18("kanfang.yuyue.db.failure"));
		}
		
		PageData page_data=new PageData<FDCAgentDetail>(page, total, size, null);
		
		
		List<FDCProject> project_list=null;
		try {
			project_list=project_dao.getAllByWxprojectId(wxproject_id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
		}
		
		List<Withdraw> withdraw_list=null;
		
		try {
			if(StringHelper.isNull(keywords)){
				withdraw_list=cash_flow.getWithdraw(wxproject_id,status);
			}else{
				withdraw_list=cash_flow.getWithdrawByName(wxproject_id,status,keywords);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("mc.yongjin.db.failure")+":"+e.getLocalizedMessage());
		}
		page_data.setData(withdraw_list);
		
		el.setAttr("page_data", page_data);
		el.setAttr("keywords", keywords);
		el.setAttr("keywords_encode", URLEncoder.encode(keywords,"utf-8"));
		el.setAttr("withdraw_list", withdraw_list);
		el.setAttr("project_list", project_list);
		el.setAttr("out_status",status);
		el.template("/WEB-INF/template/boss/yongjin/index.vm");
	}
}
